﻿Imports System.IO

Public Class BitmapManager

    Shared Bitmaps As New SortedList(Of String, Bitmap)
    Shared Thumbs As New MemoryStream

    Shared Sub Add(ByVal Key As String, ByVal Bitmap As Bitmap)
        Bitmaps.Add(Key, Bitmap)
    End Sub

    Shared Function Exists(ByVal Key As String) As Boolean
        Return Bitmaps.ContainsKey(Key)
    End Function

    Shared Function GetBitmap(ByVal Key As String)
        Return Bitmaps(Key)
    End Function

    Shared Sub Remove(ByVal Key As String)
        Bitmaps.Remove(Key)
    End Sub

    Shared Sub ReadThumb()
        Dim ThumbsFile As String = My.Computer.FileSystem.SpecialDirectories.Temp & "\thumbs.db"
        If Not My.Computer.FileSystem.FileExists(ThumbsFile) Then Exit Sub
        Dim File As New FileStream(ThumbsFile, FileMode.Open)
        Dim Buffer(File.Length - 1) As Byte
        File.Read(Buffer, 0, Buffer.Length)
        Thumbs.Write(Buffer, 0, Buffer.Length)
        File.Close()
    End Sub

    Shared Function AddThumb(ByVal Stream As Stream) As String
        Dim Start = Thumbs.Length
        Dim Length = Stream.Length
        Dim Buffer(Length - 1) As Byte
        Stream.Read(Buffer, 0, Length)
        Thumbs.Position = Thumbs.Length
        Thumbs.Write(Buffer, 0, Length)
        Stream.Close()
        Dim File As New FileStream(My.Computer.FileSystem.SpecialDirectories.Temp & "\thumbs.db", FileMode.Append)
        File.Write(Buffer, 0, Length)
        File.Close()
        Return Start & "." & Length
    End Function

    Shared Sub DeleteThumbs()
        My.Computer.FileSystem.DeleteFile(My.Computer.FileSystem.SpecialDirectories.Temp & "\thumbs.db")
    End Sub

    Shared Function GetThumb(ByVal Info As String) As Stream
        Dim Data = Split(Info, ".")
        Dim Buffer(Data(1) - 1) As Byte
        Thumbs.Position = Data(0)
        Thumbs.Read(Buffer, 0, Data(1))
        Return New MemoryStream(Buffer)
    End Function

End Class

Public Class MemoryManager
    Shared Images As New List(Of ImageInfo)
    Shared WithEvents BackgroundWorker As New System.ComponentModel.BackgroundWorker

    Public Shared Sub Register(ByVal ImageInfo As ImageInfo)
        Images.Add(ImageInfo)
    End Sub

    Private Shared Sub BackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles BackgroundWorker.DoWork
        'Try
        For Each Image In Images.ToList
            Image.Clean()
        Next
        'Catch ex As Exception
        'End Try
    End Sub

    Shared Sub Clean()
        If BackgroundWorker.IsBusy Then Exit Sub
        BackgroundWorker.RunWorkerAsync()
    End Sub

End Class